//
//  ManagementVC.m
//  qunfa
//
//  Created by Admin on 2017/8/11.
//  Copyright © 2017年 cuixiaocun. All rights reserved.
//

#import "ManagementVC.h"
#import "XMLReader.h"
#import "MangementCell.h"
#import "IsTureAlterView.h"
#import "EditViewController.h"
@interface ManagementVC ()<CXCNavgationDelegate,EditDelegate,MangementDelegate,IsTureAlterViewDelegate>
{
    int  indexNum;//多线程
    dispatch_queue_t queue;//多线程
    NSInteger indexOfPath;//cell的index
}
@end

@implementation ManagementVC
-(void)retunButtonAction
{
        [self.navigationController popViewControllerAnimated:YES];

    
}

- (void) asyncConcurrent
{
    NSLog(@"asyncConcurrent---begin");
    queue = dispatch_queue_create("test.queue", DISPATCH_QUEUE_CONCURRENT);
    
    NSLog(@"asyncConcurrent---end");
}
- (void)asynIntName
{

    dispatch_async(queue, ^{
        for (int i = 0; i < 10; ++i) {
            NSLog(@"%d------%@",indexNum,[NSThread currentThread]);
        }
        
        
    });

}

- (void)viewDidLoad {
    [super viewDidLoad];
    indexNum =0;
    
    [self asyncConcurrent];
    [self.view setBackgroundColor:BGColor];
    NavgationView *nav =[[NavgationView alloc]initWithFrame:CGRectMake(0, 0, CXCWidth, 64) with:@"信息管理" isBackBtn:@"YES" rightBtnName:@"NO"];
    [self.view addSubview:nav];
    nav.delegate=self;
    self.view.backgroundColor =BGColor;
    [self mainView];
    currentPage=0;
    [self getInfoList];
    
}
- (void)mainView
{
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setFrame:CGRectMake(0,64, CXCWidth, CXCHeight-20)];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    self.tableView.showsVerticalScrollIndicator = NO;
    
    //下拉刷新
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DemoTableHeaderView" owner:self options:nil];
    DemoTableHeaderView *headerView = (DemoTableHeaderView *)[nib objectAtIndex:0];
    self.headerView = headerView;
    //上拉加载
    nib = [[NSBundle mainBundle] loadNibNamed:@"DemoTableFooterView" owner:self options:nil];
    DemoTableFooterView *footerView = (DemoTableFooterView *)[nib objectAtIndex:0];
    self.footerView = footerView;
    infoArray = [[NSMutableArray alloc] init];
    //  [self performSelector:@selector(getInfoList)];
}
- (void)returnBtnAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return infoArray.count ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *str = [NSString stringWithFormat:@"%@",[infoArray[indexPath.row] objectForKey:@"content"]];
    
    float height = [PublicMethod heightForString:str fontSize:14 andWidth:Width*650];
    return height+700*Width;
}


- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row =[indexPath row];
    static NSString *CellIdentifier = @"Cell";
    MangementCell *cell =[tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[MangementCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:CellIdentifier ];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
    }
    NSDictionary *dict = [infoArray objectAtIndex:row];
    cell.delegate=self;
    [cell setDic:dict];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
#pragma mark - Pull to Refresh
- (void) pinHeaderView
{
    [super pinHeaderView];
    
    // do custom handling for the header view
    DemoTableHeaderView *hv = (DemoTableHeaderView *)self.headerView;
    [hv.activityIndicator startAnimating];
    hv.title.text = @"加载中...";
    [CATransaction begin];
    [self.tableView setFrame:CGRectMake(0,64, CXCWidth, CXCHeight-20)];
    
    [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
    ((DemoTableHeaderView *)self.headerView).arrowImage.hidden = YES;
    [CATransaction commit];;
}
- (void) unpinHeaderView
{
    [super unpinHeaderView];
    
    // do custom handling for the header view
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setAMSymbol:@"AM"];
    [formatter setPMSymbol:@"PM"];
    [formatter setDateFormat:@"yyyy/MM/dd hh:mm:ss a"];
    ((DemoTableHeaderView *)self.headerView).time.text = [NSString stringWithFormat:@"最后更新: %@", [formatter stringFromDate:[NSDate date]]];
    [[(DemoTableHeaderView *)self.headerView activityIndicator] stopAnimating];
}

- (void) headerViewDidScroll:(BOOL)willRefreshOnRelease scrollView:(UIScrollView *)scrollView
{
    DemoTableHeaderView *hv = (DemoTableHeaderView *)self.headerView;
    if (willRefreshOnRelease){
        hv.title.text = @"松开即可更新...";
        currentPage = 0;
        [CATransaction begin];
        [CATransaction setAnimationDuration:0.18f];
        ((DemoTableHeaderView *)self.headerView).arrowImage.transform = CATransform3DMakeRotation((M_PI / 180.0) * 180.0f, 0.0f, 0.0f, 1.0f);
        [CATransaction commit];
    }
    
    else{
        
        if ([hv.title.text isEqualToString:@"松开即可更新..."]) {
            currentPage = 0;
            [CATransaction begin];
            [CATransaction setAnimationDuration:0.18f];
            ((DemoTableHeaderView *)self.headerView).arrowImage.transform = CATransform3DIdentity;
            [CATransaction commit];
        }
        
        hv.title.text = @"下拉即可刷新...";
        [CATransaction begin];
        [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
        ((DemoTableHeaderView *)self.headerView).arrowImage.hidden = NO;
        ((DemoTableHeaderView *)self.headerView).arrowImage.transform = CATransform3DIdentity;
        [CATransaction commit];
    }
    
}
//
- (BOOL) refresh
{
    if (![super refresh])
        return NO;
    
    // Do your async call here
    // This is just a dummy data loader:
    [self performSelector:@selector(addItemsOnTop) withObject:nil afterDelay:0];
    
    
    // See -addItemsOnTop for more info on how to finish loading
    return YES;
}
#pragma mark - Load More

- (void) willBeginLoadingMore
{
    DemoTableFooterView *fv = (DemoTableFooterView *)self.footerView;
    [fv.activityIndicator startAnimating];
}

- (void) loadMoreCompleted
{
    [super loadMoreCompleted];
    
    DemoTableFooterView *fv = (DemoTableFooterView *)self.footerView;
    [fv.activityIndicator stopAnimating];
    
    if (!self.canLoadMore) {
        // Do something if there are no more items to load
        
        // We can hide the footerView by: [self setFooterViewVisibility:NO];
        
        // Just show a textual info that there are no more items to load
        fv.infoLabel.hidden = YES;
    }else{
        fv.infoLabel.hidden = NO;
    }
}
- (BOOL) loadMore
{
    if (![super loadMore])
        return NO;
    
    
    [self performSelector:@selector(addItemsOnBottom) withObject:nil afterDelay:0];
    
    
    // Inform STableViewController that we have finished loading more items
    
    return YES;
}


- (void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    DemoTableFooterView *fv = (DemoTableFooterView *)self.footerView;
    
    if (!isRefreshing && isDragging && scrollView.contentOffset.y < 0) {
        [self headerViewDidScroll:scrollView.contentOffset.y < 0 - [self headerRefreshHeight]
                       scrollView:scrollView];
    } else if (!isLoadingMore && self.canLoadMore) {
        CGFloat scrollPosition = scrollView.contentSize.height - scrollView.frame.size.height - scrollView.contentOffset.y;
        //NSLog(@"%f====%f",scrollPosition,[self footerLoadMoreHeight]);
        if (scrollPosition < [self footerLoadMoreHeight] && scrollPosition > 20) {
            
            [fv.infoLabel setText:@"上拉加载更多..."];
        }else if(scrollPosition < 20){
            //[fv.infoLabel setText:@"释放开始加载..."];
            [fv.infoLabel setText:@"正在加载..."];
            [self loadMore];
        }
        
    }
}

#pragma mark - Dummy data methods
- (void) addItemsOnTop
{
    
    currentPage=0;
    [self performSelector:@selector(getInfoList) withObject:nil afterDelay:0];
    
    DemoTableFooterView *fv = (DemoTableFooterView *)self.footerView;
    
    if (currentPage >= pageCount-1){
        self.canLoadMore = NO; // signal that there won't be any more items to load
    }else{
        self.canLoadMore = YES;
    }
    
    
    
    
    if (!self.canLoadMore) {
        fv.infoLabel.hidden = YES;
    }else{
        fv.infoLabel.hidden = NO;
    }
    
    
    // Call this to indicate that we have finished "refreshing".
    // This will then result in the headerView being unpinned (-unpinHeaderView will be called).
    [self refreshCompleted];
}


- (void) addItemsOnBottom
{
    currentPage++;
    [self performSelector:@selector(getInfoList) withObject:nil afterDelay:0];
    
    
    if (currentPage >= pageCount-1)
        self.canLoadMore = NO; // signal that there won't be any more items to load
    else
        self.canLoadMore = YES;
    
    // Inform STableViewController that we have finished loading more items
    [self loadMoreCompleted];
}
- (void)getInfoList
{
    
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
    [dic1 setDictionary:@{
                          @"memberId":[NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",[[PublicMethod getDataKey:member] objectForKey:@"id"]]] ,
                          }
     ];
    [PublicMethod AFNetworkPOSTurl:@"index.php/Home/Advert/selAdvert" paraments:dic1  addView:self.view success:^(id responseDic) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseDic options:NSJSONReadingMutableContainers error:nil];
        NSString *str =[[NSString alloc] initWithData:responseDic  encoding:NSUTF8StringEncoding];
        NSError *parseError = nil;
        if ([[NSString stringWithFormat:@"%@",[dict objectForKey:@"code"]]isEqualToString:@"0"]) {
            
            NSMutableArray *array=[[dict objectForKey:@"data"] objectForKey:@"log"];
            if (currentPage==0) {
                [infoArray removeAllObjects];
                
            }
            if ([array isKindOfClass:[NSNull class]]) {
                [self.tableView reloadData];
                
                return ;
            }
            
            
            [infoArray addObjectsFromArray:array];
            
            if ([infoArray count]==0 && currentPage==0) {
                
            }
            pageCount =infoArray.count/20;
            //判断是否加载更多
            if (array.count==0 || array.count<20){
                self.canLoadMore = NO; // signal that there won't be any more items to load
            }else{
                self.canLoadMore = NO;//要是分页的话就要改成yes并且把上面的currentPage=1注掉
            }
            
            DemoTableFooterView *fv = (DemoTableFooterView *)self.footerView;
            [fv.activityIndicator stopAnimating];
            
            if (!self.canLoadMore) {
                fv.infoLabel.hidden = YES;
            }else{
                fv.infoLabel.hidden = NO;
            }
            
            
            [self.tableView reloadData];
            if (currentPage==0) {
                //                [self.tableView setScrollsToTop:YES];
                [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
            }
            
            [self.tableView reloadData];

            
        }
        

        
    } fail:^(NSError *error) {
        
    }];
    
}

-(void)btnClick:(UITableViewCell *)cell andIsSelect:(BOOL)isSelect
{

    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
    NSString *selectStr;
//        isPush（true推送 false不推送）
    if (isSelect ==0) {
        selectStr =@"2";
    }else
    {
        selectStr =@"1";
    }
   
        [dic1 setDictionary:@{
                              @"id":[NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",[infoArray[index.row] objectForKey:@"id"]]] ,
                              @"isPush":selectStr,
                              @"memberId":[NSString stringWithFormat:@"%@",[[PublicMethod getDataKey:member] objectForKey:@"id"]],
                 
                              }];
       NSString* url =@"index.php/Home/Advert/changeAdvertPush";
       [PublicMethod AFNetworkPOSTurl:url paraments:dic1  addView:self.view success:^(id responseDic) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseDic options:NSJSONReadingMutableContainers error:nil];
            if ([ [NSString stringWithFormat:@"%@",[dict objectForKey:@"code"]]isEqualToString:@"0"]) {
                
                [MBProgressHUD showSuccess:@"设置成功" ToView:self.view];
                [infoArray [index.row] setObject:selectStr forKey:@"ispush"];
                [self.tableView reloadData];
            }
            
        } fail:^(NSError *error) {
            
        }];
        
       
        
    



}
-(void)btnClick:(UITableViewCell *)cell andInTag:(NSInteger)flag
{
    
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    indexOfPath =index.row ;

    
   if (flag==2000)
    {
        //审核通过
        IsTureAlterView *isture =[[IsTureAlterView alloc]initWithTitile:@"确认要删除吗？"];
        isture.delegate =self;
        isture.tag =180;
        [self.view addSubview:isture];
        
        
        
        
    }else if (flag==2001)
    {
        EditViewController*edit =[[EditViewController alloc]init];
        edit.dic =infoArray[indexOfPath];
        edit.delegate =self;
        [self.navigationController pushViewController:edit animated:YES];
        
    }
    
    
    
    
    
    
    
}
- (void)delete
{
    
    
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
    
    [dic1 setDictionary:@{
                          @"id":[NSString stringWithFormat:@"%@",[infoArray[indexNum] objectForKey:@"id"]] ,
                          @"memberId":[NSString stringWithFormat:@"%@",[infoArray[indexNum] objectForKey:@"memberid"]],
                          
                          }];
    NSString* url =@"index.php/Home/Advert/delAdvert";
    
    [PublicMethod AFNetworkPOSTurl:url paraments:dic1  addView:self.view success:^(id responseDic) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseDic options:NSJSONReadingMutableContainers error:nil];
        if ([ [NSString stringWithFormat:@"%@",[dict objectForKey:@"code"]]isEqualToString:@"0"]) {
            
            [MBProgressHUD showSuccess:@"删除成功" ToView:self.view];
                                [self  getInfoList ];
        }
        
    } fail:^(NSError *error) {
        
    }];
    
    
    
    
    
    
    
}
-(void)cancelBtnActinAndTheAlterView:(UIView *)alter
{
    IsTureAlterView *isture = [self.view viewWithTag:180];
    [isture removeFromSuperview];
    NSLog(@"取消");
    
}
-(void)tureBtnActionAndTheAlterView:(UIView *)alter
{
    IsTureAlterView *isture = [self.view viewWithTag:180];
    [isture removeFromSuperview];
    
    
    [self delete];

    
}
-(void)needReloadDataEdit
{
    [MBProgressHUD showSuccess:@"提交成功" ToView:self.view];

    [self getInfoList];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
